package com.linfeng.server.oauth.impl;

import com.linfeng.business.admin.dto.data.admin.SysAdminDTO;
import com.linfeng.business.admin.aggregate.AdminAggregateRoot;
import com.linfeng.component.common.response.ResponseEntity;
import com.linfeng.component.common.tools.ResponseResultTools;
import com.linfeng.server.oauth.data.AdminDetails;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Optional;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    AdminAggregateRoot adminAggregateRoot;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        ResponseEntity<SysAdminDTO> responseEntity = adminAggregateRoot.detailByLoginName(username);

        SysAdminDTO sysAdminDTO = ResponseResultTools.getData(responseEntity);

        AdminDetails adminDetails = Optional.ofNullable(sysAdminDTO)
                .map(dto -> {
                    AdminDetails details = new AdminDetails();
                    details.setUsername(sysAdminDTO.getLoginName());
                    details.setPassword(sysAdminDTO.getPassword());
                    details.setAdminId(dto.getId());

                    return details;
                }).orElse(new AdminDetails());

        return adminDetails;
    }
}
